/**
 * @desc 用户对应处理层
 */

import { PayListLogger } from '../middleware/logger';
import ErrorCode, { SuccessCode } from '../utils/errorCode';
import axios from 'axios';
const PayListModel = require('../db/payList');
const UserModel = require('../db/user');

// 异常code
const {
  Error500,
} = ErrorCode;

const updateUserTicket = async (openid: string, ticket: string) => {
  try {
    // 查询用户数据
    const result = await UserModel.find({ openid });
    if (result && result.length > 0) {
      let userTicket = result[0].ticket;
      userTicket += Number(ticket);
      // 用户表中更新票数
      await UserModel.updateOne({ openid }, { ticket: userTicket });
    } else {
      PayListLogger({
        name: `支付金额增加用户票数接口出错`,
        info: `查询用户失败, 用户openid: ${openid}, 需要增加的票数为: ${ticket}`,
      });
    }
  } catch(err) {
    PayListLogger({
      name: `支付金额增加用户票数接口出错`,
      info: `票数：${ticket}, 用户openid: ${openid}`,
      err: JSON.stringify(err),
    });
  }
}

/**
 * 保存支付信息
 * @param  用户支付信息
 * @returns 
 */
export const CPayListSave = (openid: string, passopenid: string, money: string, ticket: string, time: string, code: string) => {
  return new Promise(async (resolve, reject) => {
    try {
      //验证code数据是否合法
      const istrueData = await checkCode(code, passopenid)
      if(!istrueData){
        reject(Error500)
        return
      }
      updateUserTicket(openid, ticket);
      // 支付记录
      PayListLogger({
        name: '支付请求成功，保存支付信息',
        openid,
        passopenid,
        money,
        ticket,
        time
      });
      const vPayListModel = new PayListModel({
        openid: openid || '',
        passopenid: passopenid || '',
        money: money || '',
        ticket: ticket || '',
        time: time || '',
      });
      await vPayListModel.save();
      resolve({
        ...SuccessCode,
      });
    } catch (err: any) {
      PayListLogger({
        name: `支付金额接口出错`,
      info: `票数：${ticket}, 用户openid: ${openid}, 投票人: ${passopenid}, 支付金额: ${money}, 支付时间: ${time}`,
      err: JSON.stringify(err),
      });
      reject(Error500);
    }
  });
}


const checkCode = async (sCode: String, sOpenid: String) => {
  const APPID = "wxe981841c8b4cdb53" 
  const APPSECRET = "9bab5415b9d121040cac7b4fbd0ce9cc"
  // 通过code换取网页授权access_token
  const authorizationRes = await axios.get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${APPID}&secret=${APPSECRET}&code=${sCode}&grant_type=authorization_code`)
  const { openid } = authorizationRes.data
  return sOpenid === openid
}